package com.xingfly.product.product;

import com.xingfly.product.sdk.command.CreateProductCommand;
import com.xingfly.product.sdk.command.UpdateProductNameCommand;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by SuperS on 2019/11/21.
 *
 * @author SuperS
 */
@Service
public class ProductAppService {

    private ProductRepository productRepository;

    public ProductAppService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    @Transactional(rollbackFor = Exception.class)
    public ProductId create(CreateProductCommand command) {
        Product product = Product.create(command.getName(), command.getDescription(), command.getPrice(), command.getCategoryId());
        Product p = productRepository.save(product);
        return p.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    public ProductId updateProduceName(String id, UpdateProductNameCommand command) {
        Product product = productRepository.findById(ProductId.from(id))
                .orElseThrow(() -> new RuntimeException("Product Not Found!"));
        product.updateName(command.getName());
        productRepository.save(product);
        return product.getId();
    }

}
